import scrapy
from scrapy_dangdang_04.items import ScrapyDangdang04Item


class DangSpider(scrapy.Spider):
    name = "dang"
    allowed_domains = ["category.dangdang.com"]
    start_urls = ["https://category.dangdang.com/cp01.01.02.00.00.00.html"]

    base_url = "https://category.dangdang.com/pg"
    page = 1

    def parse(self, response):
        # pipelines 下载数据
        # items 定义数据结构
        # src = //ul[@class="bigimg"]//li//a//img/@src
        # alt = //ul[@class="bigimg"]//li//a//img/@alt
        # price = //ul[@class="bigimg"]/li//span[@class="search_now_price"]/text()
        # 所有的 selector 的对象 都可以再次调用 xpath 方法
        li_list = response.xpath('//ul[@class="bigimg"]//li')
        for li in li_list:
            src = li.xpath('./a//img/@data-original').extract_first()
            if src:
                src = f"https:{src}"
            else:
                src = f"https:{li.xpath('./a//img/@src').extract_first()}"
            name = li.xpath('./a//img/@alt').extract_first()[1::]
            price = li.xpath('./p//span[@class="search_now_price"]/text()').extract_first()

            book = ScrapyDangdang04Item(src=src, name=name, price=price)
            # 获取一个 book 就将 book 交给 pipelines
            yield book

        if self.page < 100:
            self.page += 1
            url = f"{self.base_url}{self.page}-cp01.01.02.00.00.00.html"
            # 怎么去调用 parse 方法
            # scrapy.Request 就是 scrapy 给我们提供的请求对象
            # 该请求对象的 get 方法可以向指定的
            yield scrapy.Request(url=url, callback=self.parse)